package com.fastloan.safe.core.perms;

import com.kawins.result.ResultTo;
import com.kawins.shiro.temp.util.ShiroKit;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * @author rankai
 *         createTime 2017-09-2017/9/27 13:59
 */
@Aspect
@Component
public class LicensingAspect {

    @Pointcut("@annotation(com.fastloan.safe.core.perms.Licensing)")
    public void licensingAspect() {
    }

    @Around("licensingAspect()")
    public Object aroundMethod(ProceedingJoinPoint joinPoint) throws Throwable {
        ResultTo resultTo = (ResultTo) joinPoint.proceed();
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        Method method = methodSignature.getMethod();
        Licensing licensing = method.getAnnotation(Licensing.class);
        String[] value = licensing.value();
        Map<String, Boolean> map = new HashMap<>(0);
        for (int i = 0; i < value.length; i++) {
            String[] split = value[i].split("#");
            if (split.length == 2) {
                map.put(split[0], ShiroKit.hasPermission(split[1]));
            }
        }
        if (resultTo != null) {
            resultTo.setPerms(map);
        }
        return resultTo;
    }
}
